import threading
from concurrent.futures import ThreadPoolExecutor
import time
from typing import List, Callable
from datetime import datetime
from common.logger import logger

class TaskExecutor:
    def __init__(self, max_workers: int = 4, check_interval: int = 5):
        self.pool = ThreadPoolExecutor(max_workers=max_workers)
        self.check_interval = check_interval
        self.running = False
        self.tasks_queue = []
        self._lock = threading.Lock()

    def start(self):
        """启动任务执行器"""
        self.running = True
        threading.Thread(target=self._task_checker, daemon=True).start()
        logger.info("任务执行器已启动")

    def stop(self):
        """停止任务执行器"""
        self.running = False
        self.pool.shutdown(wait=True)
        logger.info("任务执行器已停止")

    def add_task(self, task: Callable, *args, **kwargs):
        """添加任务到队列"""
        with self._lock:
            self.tasks_queue.append((task, args, kwargs))
        logger.info(f"新任务已添加: {task.__name__}")

    def _task_checker(self):
        """任务检查线程"""
        while self.running:
            try:
                self._check_and_execute_tasks()
            except Exception as e:
                logger.error(f"任务检查出错: {str(e)}")
            time.sleep(self.check_interval)

    def _check_and_execute_tasks(self):
        """检查并执行任务"""
        with self._lock:
            if not self.tasks_queue:
                return

            task, args, kwargs = self.tasks_queue.pop(0)
            try:
                future = self.pool.submit(task, *args, **kwargs)
                future.add_done_callback(self._task_callback)
                logger.info(f"任务已提交执行: {task.__name__}")
            except Exception as e:
                logger.error(f"任务提交失败: {str(e)}")

    def _task_callback(self, future):
        """任务完成回调"""
        try:
            result = future.result()
            logger.info(f"任务执行完成: {result}")
        except Exception as e:
            logger.error(f"任务执行失败: {str(e)}")

# 使用示例
if __name__ == "__main__":
    def example_task(task_id: int):
        logger.info(f"开始执行任务 {task_id}")
        time.sleep(2)  # 模拟耗时操作
        return f"任务 {task_id} 执行完成"

    # 创建任务执行器实例
    executor = TaskExecutor(max_workers=2, check_interval=3)
    executor.start()

    # 添加一些测试任务
    for i in range(5):
        executor.add_task(example_task, i)

    # 运行一段时间后停止
    time.sleep(20)
    executor.stop()